#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
查询fund_download_status表的下载状态统计
"""

import os
import sys

# 设置Django环境
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wealth_backend.settings')

try:
    import django  # type: ignore
    django.setup()
    from django.db import connection  # type: ignore
except ImportError:
    print('Django未安装或配置错误')
    sys.exit(1)

def query_download_status():
    """查询下载状态统计"""
    cursor = connection.cursor()
    
    try:
        # 查询各状态的统计
        cursor.execute("""
            SELECT download_status, COUNT(*) as count 
            FROM fund_download_status 
            GROUP BY download_status 
            ORDER BY download_status
        """)
        
        results = cursor.fetchall()
        
        print('fund_download_status表下载状态统计:')
        print('=' * 50)
        print(f"{'状态':<20} {'条数':<10}")
        print('-' * 50)
        
        total_count = 0
        pending_count = 0
        
        for row in results:
            status = row[0] if row[0] else 'NULL'
            count = row[1]
            total_count += count
            
            if status in ['pending', 'failed', 'NULL']:
                pending_count += count
                
            print(f'{status:<20} {count:<10}')
        
        print('-' * 50)
        print(f"{'总计':<20} {total_count:<10}")
        print(f"{'未完成下载':<20} {pending_count:<10}")
        
        # 查询具体的未完成状态详情
        cursor.execute("""
            SELECT download_status, COUNT(*) as count 
            FROM fund_download_status 
            WHERE download_status IN ('pending', 'failed') OR download_status IS NULL
            GROUP BY download_status 
            ORDER BY download_status
        """)
        
        pending_results = cursor.fetchall()
        
        if pending_results:
            print('\n未完成下载详情:')
            print('=' * 30)
            for row in pending_results:
                status = row[0] if row[0] else 'NULL'
                count = row[1]
                print(f'{status}: {count}条')
                
    except Exception as e:
        print(f'查询出错: {e}')
    finally:
        cursor.close()

if __name__ == '__main__':
    query_download_status()